<template>
	<!-- 销售弹窗 -->
	<el-dialog v-model="visible" title="商品销售" width="500px" :before-close="handleClose">
		<el-form ref="formRef" :model="saleForm" :rules="rules" label-width="100px">
			<el-form-item label="商品码">
				<span>{{ currentProduct.code }}</span>
			</el-form-item>
			<el-form-item label="当前零售价">
				<span>¥{{ currentProduct.price }}</span>
			</el-form-item>
			<el-form-item label="库存数量">
				<span>{{ currentProduct.quantity }}</span>
			</el-form-item>
			<el-form-item label="销售数量" prop="quantity">
				<el-input-number
					v-model="saleForm.quantity"
					:min="1"
					:max="currentProduct.quantity"
					:precision="0"
					style="width: 100%"
				/>
			</el-form-item>
			<el-form-item label="价格方式" prop="priceType">
				<el-radio-group v-model="saleForm.priceType">
					<el-radio label="retail">零售价</el-radio>
					<el-radio label="discount">折扣</el-radio>
					<el-radio label="fixed">一口价</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="saleForm.priceType === 'discount'" label="折扣率" prop="discount">
				<el-input-number
					v-model="saleForm.discount"
					:min="0"
					:max="1"
					:step="0.1"
					:precision="2"
					style="width: 100%"
				/>
			</el-form-item>
			<el-form-item v-if="saleForm.priceType === 'fixed'" label="一口价" prop="fixedPrice">
				<el-input-number
					v-model="saleForm.fixedPrice"
					:min="0"
					:precision="2"
					:step="0.1"
					style="width: 100%"
				/>
			</el-form-item>
			<el-form-item label="应收金额">
				<span class="text-xl font-bold text-red-500">
					¥{{ calculateTotal.toFixed(2) }}
				</span>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button
					type="primary"
					class="!rounded-button whitespace-nowrap"
					@click="confirmSale"
					:loading="loading"
				>
					确认销售
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useCool } from '/@/cool';

interface Product {
	id?: number;
	code: string;
	name: string;
	price: number;
	quantity: number;
}

interface SaleForm {
	quantity: number;
	priceType: 'retail' | 'discount' | 'fixed';
	discount: number;
	fixedPrice: number;
}

const { service } = useCool();

const visible = ref(false);
const loading = ref(false);
const formRef = ref<FormInstance>();

const currentProduct = ref<Product>({
	code: '',
	name: '',
	price: 0,
	quantity: 0
});

const saleForm = reactive<SaleForm>({
	quantity: 1,
	priceType: 'retail',
	discount: 1,
	fixedPrice: 0
});

const rules: FormRules = {
	quantity: [
		{ required: true, message: '请输入销售数量', trigger: 'blur' },
		{ type: 'number', min: 1, message: '销售数量不能小于1', trigger: 'blur' }
	],
	priceType: [{ required: true, message: '请选择价格方式', trigger: 'change' }],
	discount: [
		{ required: true, message: '请输入折扣率', trigger: 'blur' },
		{ type: 'number', min: 0, max: 1, message: '折扣率必须在0-1之间', trigger: 'blur' }
	],
	fixedPrice: [
		{ required: true, message: '请输入一口价', trigger: 'blur' },
		{ type: 'number', min: 0, message: '一口价不能小于0', trigger: 'blur' }
	]
};

// 计算应收金额
const calculateTotal = computed(() => {
	const quantity = saleForm.quantity || 0;
	const basePrice = currentProduct.value.price || 0;

	switch (saleForm.priceType) {
		case 'retail':
			return quantity * basePrice;
		case 'discount':
			return quantity * basePrice * (saleForm.discount || 0);
		case 'fixed':
			return quantity * (saleForm.fixedPrice || 0);
		default:
			return 0;
	}
});

const emit = defineEmits<{
	success: [];
}>();

// 打开弹窗
const open = (product: Product) => {
	visible.value = true;
	Object.assign(currentProduct.value, product);
	resetForm();
};

// 关闭弹窗
const handleClose = () => {
	visible.value = false;
	resetForm();
};

// 重置表单
const resetForm = () => {
	formRef.value?.resetFields();
	Object.assign(saleForm, {
		quantity: 1,
		priceType: 'retail',
		discount: 1,
		fixedPrice: 0
	});
};

// 确认销售
const confirmSale = async () => {
	if (!formRef.value) return;

	try {
		await formRef.value.validate();
		loading.value = true;

		// 计算折后单价
		const originalPrice = currentProduct.value.price;
		let discountedPrice = originalPrice;
		let priceType = 0; // 0-原价 1-折扣价 2-一口价

		switch (saleForm.priceType) {
			case 'retail':
				priceType = 0;
				discountedPrice = originalPrice;
				break;
			case 'discount':
				priceType = 1;
				discountedPrice = originalPrice * saleForm.discount;
				break;
			case 'fixed':
				priceType = 2;
				discountedPrice = saleForm.fixedPrice;
				break;
		}

		const saleData = {
			productId: currentProduct.value.id,
			itemCode: currentProduct.value.code,
			barcode: currentProduct.value.code, // 假设商品码和条形码相同，实际应该从商品信息中获取
			quantity: saleForm.quantity,
			originalPrice: originalPrice,
			priceType: priceType,
			discountedPrice: discountedPrice,
			totalAmount: calculateTotal.value
		};

		// 调用销售接口
		await service.ling.sellProduct(saleData);
		ElMessage.success('销售成功');

		emit('success');
		handleClose();
	} catch (error) {
		console.error('销售失败:', error);
		ElMessage.error('销售失败');
	} finally {
		loading.value = false;
	}
};

defineExpose({
	open
});
</script>

<style lang="scss" scoped>
.dialog-footer {
	text-align: right;
}

.text-xl {
	font-size: 1.25rem;
}

.font-bold {
	font-weight: bold;
}

.text-red-500 {
	color: #ef4444;
}
</style>
